// 同步一下 md5 main.js  gruntfile  image.js utils(两个背景方法,timestamp.toString())
define(["../libs/uploadfile","utils"], function (uploadfile,utils) {
    function pageLogic(config) {
        this.pageview = config.pageview;
        this.templateVisibleRange = [];  //可见范围选中数组
        this.atRange = [];  //@某人选中数组

        this.data = this.pageview.showPageParams.data;
        if(this.data){
            this.id = this.data.id;
        } else {
             this.id = null;
        }

        this.neeedShowConfirm = true;

        this.pageview.config.ownerPage.plugin.reloadType = "";
		this.fromSummary = this.pageview.showPageParams.isSummary ? true:false;
		this.summaryData = this.pageview.showPageParams.summaryData;
        this.templateData = this.pageview.showPageParams.templateData;

    }

    pageLogic.prototype = {

        uploader_button_click:function () {
            if(this.uploader_repeat.datasource.length >= 9){
                this.pageview.showTip({
                    text: "最多只能上传9份文件!"
                });
                return;
            }
          this.pageview.refs.file_upload_input.input.click();
        },

        file_upload_input_didmount: function (sender, params) {
            var fileView = sender.$el.find("input[type='file']");
            // fileView.attr('accept', 'image/gif,image/jpeg,image/png,image/jpg');
            // var uploadUrl = this.pageview.pageManager.appConfig.taskHost + "/taskFile";
            var uploadUrl = utils.getUrl("/diaryFile/?token="+this.pageview.params.token);
            //var uploadUrl = "/projectFile/taskFile";
            var _this = this;
            var fileObj = '';
            //上传附件
            // valid_extensions: ["png", "jpg", "jpeg", "gif", "bmp",'pic'],
            fileView.ajaxfileupload({
                action: uploadUrl,
                validate_extensions:false,
                onStart: function(){
                  _this.pageview.showSubmiting({
                    text:"正在上传...",
                    successText:null,
                    errorText:"上传失败"
                  });
                },
                onError:function(e){
                  _this.pageview.showTip({
                      text: "上传失败！"
                  });
                  _this.pageview.hideSubmiting(true);
                },

                onComplete: function (res) {
                  try{
                    _this.pageview.hideSubmiting(true);
                  }catch(e){

                  }
                    if (res.code === 0 && res.data && res.data.length > 0) {
                        fileObj = res.data[0];
                        var maxSize = 10 * 1000 * 10000; //不能大于10M
                        if (fileObj.fileSize > maxSize) {
                            _this.pageview.showTip({
                                text: "文件不能大于100M"
                            });
                            return;
                        }
                        _this.pageview.refs.file_upload_input.input.val("");
                        _this.addTaskAttachFile(fileObj);
                    } else {
						console.log(res);
                        _this.pageview.showTip({
                            text: "只能上传图片"
                        });
                    }
                }
            });
        },
        button_left_click: function (sender) {
            this.add_close_button_click();
        },
        uploader_repeat_init:function(sender,params){
            this.uploader_repeat = sender;
        },
        uploader_repeat_item_init:function(sender,params){
            var srcPath = "./"+this.getIconPath(sender.datasource.fileExtension);
            sender.config.src = srcPath;
        },
        uploader_repeat_item_del_click:function(sender){
          sender.rowInstance.remove();
        },
        addTaskAttachFile:function(fileObj){
          fileObj.iconsrc = this.getIconPath(fileObj.fileExtension);
          this.pageview.refs.uploader_repeat.addItem(fileObj, 0);
        },

        getIconPath: function(ext) {
        	if( ~['.jpg', '.jpeg', '.png', '.gif', '.bmp'].indexOf(ext) ) {
        		return 'imgs/image_file.png';
        	} else if( ~['.doc', '.docx'].indexOf(ext) ) {
        		return 'imgs/word@2x.png';
        	} else if( ~['.xls', '.xlsx'].indexOf(ext) ) {
        		return 'imgs/excel@2x.png';
        	} else if( ~['.ppt', '.pptx'].indexOf(ext) ) {
        		return 'imgs/ppt@2x.png';
        	} else {
        		return 'imgs/file.png';
        	}
        },
        main_body_init:function(sender){
            var _this = this;
            if(this.data){
                //编辑 , 不能保存为草稿
                this.pageview.delegate("main_body_inner_statusview",function(target){
                    _this.pageview.refs.main_body_inner_statusview.changeStatus("main_body_inner");
                    _this.add_dailyrender_render(_this.data.content);
                    _this.add_title.setText(_this.data.templateName);
                });
                this.templateVisibleRange = this.data.range||[];
                for(var i=0,j=this.templateVisibleRange.length;i<j;i++){
                  var templateVisibleRangeItem = this.templateVisibleRange[i];
                  templateVisibleRangeItem.name = templateVisibleRangeItem.userName||templateVisibleRangeItem.teamName;
                }
                if(this.data.diaryTime){
                    this.pageview.delegate("diaryTime_Time",function(target){
                      target.setValue(utils.ConvertDateToStr(_this.data.diaryTime));
                    });
                }

                this.pageview.delegate("tips_repeat",function(target){
                  target.bindData(_this.templateVisibleRange);
                });
                var fileData = this.data.fileStr||[];
                this.pageview.delegate("uploader_repeat",function(target){
                    target.bindData(fileData);
                });

                if(this.pageview.config.ownerPage.plugin.fullPageKey !== "commonpage_draft"){
                    this.pageview.delegate("button_mid",function(target){
                        target.$el.addClass("displaynone");
                    });
                }

            }else{
                //添加

                _this.pageview.ajax({
                    type:'get',
                    url:'/diary/lastVisibleRange',
                    success:function (res) {
                        if(res.code===0){
                            _this.templateVisibleRange = res.data.ranges||[];
                            for(var i=0,j=_this.templateVisibleRange.length-1;i<=j;j--){
                                var templateVisibleRangeItem = _this.templateVisibleRange[j];
                                if(templateVisibleRangeItem.userName||templateVisibleRangeItem.teamName){
                                    templateVisibleRangeItem.name = templateVisibleRangeItem.userName||templateVisibleRangeItem.teamName;
                                }else{
                                    _this.templateVisibleRange.pop();
                                }

                            }
                            _this.pageview.delegate("tips_repeat",function(target){
                                target.bindData(_this.templateVisibleRange);
                            });
                        }
                    }
                });

                this.pageview.delegate("button_mid",function(target){
                    target.$el.removeClass("displaynone");
                });
            }
			if(this.fromSummary){
				//来自日志汇总
                this.add_title.setText(this.templateData.title);
				this.pageview.delegate("main_body_inner_statusview",function(target){
					_this.pageview.refs.main_body_inner_statusview.changeStatus("main_body_inner");
					//第一 结构取出来
					var content = _this.summaryData[0].datasource.content;
					content = JSON.parse(content);

					// 第二部 往结构填充汇总数据
					for(var i = 1 ; i < _this.summaryData.length ; i++){
						var itemData = _this.summaryData[i].datasource.content;
						itemData = JSON.parse(itemData);
						for(var ii=0,jj=itemData.length;ii<jj;ii++){
							var columnInfo = itemData[ii];
							if(columnInfo.type==="InputText"){
								content[ii].content = content[ii].content+"\n"+columnInfo.content;
							}
							if(columnInfo.type==="InputTextNum"){
								columnInfo.value = !columnInfo.value?0:columnInfo.value;
								var num1 = isNaN(columnInfo.value) ?0:parseInt(columnInfo.value);
								content[ii].value = !content[ii].value?0:content[ii].value;
								var num2 = isNaN(content[ii].value) ?0: parseInt(content[ii].value);
								content[ii].value = num1 + num2;

                                // if(ii===jj-1){
                                //     content[ii].content = content[ii].value;
                                // }
                            }

						}
					}
					_this.add_dailyrender_render(content);

				});
			}
		},
        button_right_click: function (sender) {
            var _this = this;

            var submitData = _this.getParams();
            if(submitData===false){
              return;
            }
            var url = "/diary/diaryCommit";

            if(this.id!==null){
                url = "/diary/edit";
                if(this.pageview.config.ownerPage.plugin.fullPageKey !== "commonpage_draft"){
                    // url = "/diary/edit";


                }else{
                    submitData.dataStatus = 1;
                    // delete submitData.dataType;
                }
                submitData.id = this.id;

                submitData.longitude = submitData.longitude||"0";
                submitData.latitude = submitData.latitude||"0";
                submitData.location = "";

            }else{
              this.id = null;
            }
            this.pageview.showSubmiting({
                text:"正在处理中...",
                successText:"日志提交成功"
            });
            this.pageview.ajax({
                url:url,
                type:"POST",
                data:submitData,
                timeout:1000000,
                success:function (data) {
                     if(data.code === 0){

                       _this.neeedShowConfirm = false;

                          if(_this.id===null){
                            _this.pageview.config.ownerPage.plugin.reloadType = "new";
                            data.data.avatar = _this.pageview.pageManager.userInfo.head_img_url;
                            data.data.createTime = new Date().valueOf();
                            var a = ["其他","日报","周报","月报","其他"];
                            if(_this.templateInfo){
                                data.data.diaryType = _this.templateInfo.dataType;
                                data.data.diaryTypeName =  a[_this.templateInfo.dataType]||"其他";
                            }
                            data.data.like = {isLike:0,likeNum:0};
                            if(data.data.at){
                                for(var i=0;i<data.data.at.length;i++){
                                    data.data.at[i].replayUserName = data.data.at[i].userName;
                                }
                            }
                            //_this.pageview.showPageParams.fullPageKey==="commonpage_team"||
                            if(_this.pageview.showPageParams.fullPageKey==="commonpage_my"){
                                 _this.pageview.config.ownerPage.plugin.newRowData = data.data;
                            }

                          }else{
                            _this.pageview.config.ownerPage.plugin.reloadType = "modify";
                            _this.pageview.config.ownerPage.plugin.reloadId = _this.id;
                            if(_this.pageview.config.ownerPage.plugin.fullPageKey === "commonpage_draft"){
                                _this.pageview.config.ownerPage.plugin.reloadType = "draftSend";
                            }
                          }

                         setTimeout(function(){
                             _this.add_close_button_click();   //提交成功后关闭
                         },1000);
                     }
                    _this.pageview.hideSubmiting(data.code === 0);
                },
                error:function(){
                    _this.pageview.hideSubmiting(false);
                }

            });
        },
        button_mid_init:function(sender){
            this.button_mid = sender;
        },
        button_mid_click:function(sender){
            var _this = this;
            var url = "/diary/diaryCommitDraft";

            var  submitData= _this.getParams();
            if(submitData===false){
              return;
            }
            this.pageview.showSubmiting({
                text:"正在处理中...",
                successText:null
            });

            if(this.id!==null){
                url = "/diary/edit";
                submitData.id = this.id;
            }
            this.pageview.ajax({
                url:url,
                type:"POST",
                data:submitData,
                success:function (data) {
                    if(data.code === 0){
                       _this.neeedShowConfirm = false;
                        _this.pageview.config.ownerPage.plugin.reloadType = "savedraft";
                        _this.pageview.showTip({
                            text:"日志草稿保存成功",
                            duration:1000
                        });
                        setTimeout(function(){
                            _this.add_close_button_click();   //提交成功后关闭
                        },1000);
                        if(_this.pageview.config.ownerPage.plugin.fullPageKey === "commonpage_draft"){
                            if(_this.id!==null){
                                _this.pageview.config.ownerPage.plugin.reloadType = "modify";
                                _this.pageview.config.ownerPage.plugin.reloadId = _this.id;
                            }else{
                                _this.pageview.config.ownerPage.plugin.reloadType = "new";
                                data.data.avatar = _this.pageview.pageManager.userInfo.head_img_url;
                                data.data.createTime = new Date().valueOf();
                                var a = ["其他","日报","周报","月报","其他"];
                                if(_this.templateInfo){
                                    data.data.diaryType = _this.templateInfo.dataType;
                                    data.data.diaryTypeName =  a[_this.templateInfo.dataType]||"其他";
                                }
                                data.data.like = {isLike:0,likeNum:0};
                                data.data.favorite = {favoriteNum:0,isFavorite:0};
                                if(data.data.at){
                                    for(var i=0;i<data.data.at.length;i++){
                                        data.data.at[i].replayUserName = data.data.at[i].userName;
                                    }
                                }

                                _this.pageview.config.ownerPage.plugin.newRowData = data.data;
                            }
                        }

                    }
                    _this.pageview.hideSubmiting(data.code === 0);
                },
                error:function(){
                    _this.pageview.hideSubmiting(false);
                }

            });
        },
        diaryTime_Time_change:function(sender,params){
            if(utils.compareDate(params.date,new Date())===1){
                this.pageview.showTip({text:"所选时间不能晚于今天"});
                sender.setValue(new Date());
            }
        },
        getParams:function(){
            var params = {};
            params.gather = 0;  //来自非汇总
            params.diaryTime = this.pageview.refs.diaryTime_Time.getValue().str;
            if(this.data){
                params.templateId = this.data.templateId;
                params.templateName = this.data.templateName;
                params.version = this.data.version;
            }
            else if(this.fromSummary){
                //来自汇总
                params.templateId = this.templateData.id;
                params.templateName = this.templateData.title;
                params.version = this.templateData.version;
                params.gather = 1; //1来自汇总
            }
            else{
                params.templateId = this.selectedMode.datasource.id;
                params.templateName = this.selectedMode.datasource.title;
                params.version = this.selectedMode.datasource.version;

            }
            params.source = 3;  //3表示来源于web
            var c = this.pageview.refs.add_dailyrender.getValue();
            if(c===null){
              return false;
            }
            params.content = JSON.stringify(c);

            // var Re = this.pageview.refs.add_dailyrender.getValue();
            var viewRange = [];
            this.templateVisibleRange = this.templateVisibleRange||[];

            for(var i=0,j=this.templateVisibleRange.length;i<j;i++){
              var itemData = this.templateVisibleRange[i];
              if(itemData.dataType===1){
                 viewRange.push({dataType:1,teamId:itemData.teamId,teamName:itemData.teamName});
              }
              if(itemData.dataType===4){
                 viewRange.push({dataType:4,memberId:itemData.memberId});
              }
              if(itemData.dataType===3){
                 viewRange.push({dataType:3,teamId:itemData.teamId,teamName:itemData.teamName});
              }
            }

            var needAddAtPersonToViewRange =viewRange.length!==0;

            this.atRange = this.atRange||[];
            var atPersons = [];
            for(var ii=0,jj=this.atRange.length;ii<jj;ii++){
                atPersons.push({userName:this.atRange[ii].userName,memberId:this.atRange[ii].memberId,szId:this.atRange[ii].spaceId});
                if(needAddAtPersonToViewRange){
                    if(this.atRange[ii].dataType===1){
                        viewRange.push({dataType:1,teamId:this.atRange[ii].teamId,teamName:this.atRange[ii].teamName});
                    }
                    if(this.atRange[ii].dataType===4){
                        viewRange.push({dataType:4,memberId:this.atRange[ii].memberId});
                    }
                    if(this.atRange[ii].dataType===3){
                        viewRange.push({dataType:3,teamId:this.atRange[ii].teamId,teamName:this.atRange[ii].teamName});
                    }
                }

            }
            params.atStr = JSON.stringify(atPersons);

            // params.visibleRange = viewRange.length===0?0:1;
            params.visibleRange = viewRange.length===0?3:1;   //可见范围默认为本部门，传3
            params.visibleRangeStr = JSON.stringify(viewRange);

            //fixed here

            var dataType;
            if(this.templateInfo){
              dataType = this.templateInfo.dataType;
            }else if(this.fromSummary){
                // dataType = this.templateData.dataType;
            }
            else{
              dataType = this.data.dataType;
            }
            params.dataType = dataType;

            // createTime: 1480298334955
            // creatorId: 2834638creatorName: "胡小中"
            // extensionType: 1
            // fileExtension: ".png"
            // fileKey: "http://115.29.39.62/diary/diaryFile/3W4aKtglo6UhlJpPXAzpUpC1BCxii6R3.png"
            // fileName: "empty@2x"
            // fileSize: 6789
            // fileSizeText: "6KB"
            // id: 248timeLong: null
            //[{fileName:'sddffg.png',fileSize:122334,fileKey:'http://sddffg.png',fileExtension:'.png'}]
            var files=[];
            for(var iii=0,jjj=this.pageview.refs.uploader_repeat.datasource.length;iii<jjj;iii++){
              var redata = this.pageview.refs.uploader_repeat.datasource[iii];
              if(redata.fileExtension.indexOf(".")===0){

              }else{
                redata.fileExtension = "."+redata.fileExtension;
              }
              files.push({
                fileName:redata.fileName+redata.fileExtension,
                fileSize:redata.fileSize,
                fileExtension:redata.fileExtension,
                fileKey:redata.fileKey,
              });
            }

            // params.fileStr = JSON.stringify([{"fileName":"工作中心-视觉验收.key","fileSize":2035386,"fileExtension":".key","fileKey":"http://115.29.39.62/logger/diaryFile/aq8Q2WKUXzEfa0Ishy4RnpnxUPZ9vqBz.key"},{"fileName":"6xls","fileSize":23040,"fileExtension":"xls","fileKey":"http://115.29.39.62/logger/diaryFile/qrGaUBNqY3lsGRjLuMGfb694qk8OZLNd.xls"},{"fileName":"wcfuture_m.png","fileSize":9957,"fileExtension":".png","fileKey":"http://115.29.39.62/logger/diaryFile/pzCybgsGPcMOnHsfcKNXIGgYowTX8oAx.png"}]);
            //[{fileName:'sddffg.png',fileSize:122334,fileKey:'http://sddffg.png',fileExtension:'.png'}]
            params.fileStr = JSON.stringify(files);
            return params;
        },
        add_dailyrender_showcanledar: function (sender, params) {
            var _this = this;
            // params.e.stopPropagation();
            // params.e.preventDefault();
            this.dateItem = params.itemInstance;

            var dateStr = this.dateItem.getValue().value;
            params.itemInstance.$el[0].scrollIntoView();
           window.setTimeout(function(){
             var pos =  params.itemInstance.$el.offset();
             _this.pageview.refs.common_calendar.show(dateStr, {top: pos.top+20, left: 22});
           },30);
            //main_body_inner
        },
        common_calendar_change: function (sender, params) {
            this.dateItem.setValue(params.str);
        },

        template_repeat_init:function(sender,params){
            this.template_repeat = sender;
            var _this = this;
            this.pageview.refs.main_body.showLoading({
                text:"正在加载",
                loadingColor:"#000",
                reloadCallback:function () {
                    _this._loadTempalteData();
                }
            });

            _this._loadTempalteData();
        },
        _loadTempalteData:function(){
            //ajax
            var _this = this;
            this.pageview.ajax({
                url: "/template/list",
                type: "GET",
                data: {
                    pageNumber:1,
                    pageSize:1000,
                    client:"app"
                },
                success: function (data) {
                    if (data.code === 0) {
                        // window.setTimeout(function () {
                        //         _this.pageview.refs.main_body.hideLoading(true);
                        //         _this.template_repeat.bindData(data.data.list);
                        //     },1000);
                          _this.pageview.refs.main_body.hideLoading(true);
                          _this.template_repeat.bindData(data.data);
                    }
                    // _this.pageview.hideSubmiting(data.code === 0);
                },
                error: function () {
                    // _this.pageview.hideSubmiting(false);
                }
            });

            //_this.pageview.hideLoading(false);
        },
        onPageBeforeClose:function(){
          //main_body_inner_statusview
          if(this.neeedShowConfirm === false){
            return true;
          }
          if(this.pageview.refs.main_body_inner_statusview.curStatusKey!=="main_body_inner"){
            return true;
          }
          return window.confirm("您的日志还没提交，确定要放弃编辑吗？");
        },
        // del_dialog_cancelbtn_click:function(){
        //     this.pageview.hideDialog("del_dialog");
        // },
        // del_dialog_okbtn_click:function(sender){
        //     var _this = this;
        //     this.pageview.hideDialog("del_dialog");
        //     this.pageview.close();
        // },
        template_repeat_itemclick:function (sender,params) {
            // alert(sender.datasource.id);
            var _this = this;

            _this.pageview.ajax({
                type:'get',
                url:'/diary/lastVisibleRange?templateId='+sender.datasource.id,
                success:function (res) {
                    if(res.code===0){
                        _this.templateVisibleRange = res.data.ranges||[];
                        for(var i=0,j=_this.templateVisibleRange.length-1;i<=j;j--){
                            var templateVisibleRangeItem = _this.templateVisibleRange[j];
                            if(templateVisibleRangeItem.userName||templateVisibleRangeItem.teamName){
                                templateVisibleRangeItem.name = templateVisibleRangeItem.userName||templateVisibleRangeItem.teamName;
                            }else{
                                _this.templateVisibleRange.pop();
                            }

                        }
                        _this.pageview.delegate("tips_repeat",function(target){
                            target.bindData(_this.templateVisibleRange);
                        });
                    }
                }
            });
            this.templateInfo = sender.datasource;
            var data = JSON.parse(sender.datasource.content);
            this.add_title.setText(sender.datasource.title);
            this.selectedMode = sender;  //选中的模版
            this.pageview.refs.main_body_inner_statusview.changeStatus("main_body_inner");
            this.add_dailyrender_render(data);
        },
        main_body_inner_init:function(){

        },
        add_dailyrender_init:function(sender,params){
            this.add_dailyrender = sender;
        },
        //createLayout add_dailyrender
        add_dailyrender_render:function (data) {
            var _this = this;
            this.pageview.delegate("add_dailyrender",function(target){
                target.createLayout(data);
            });

        },
        add_close_button_click:function(sender, params){
            this.pageview.close();
        },
        add_title_init:function(sender){
            this.add_title = sender;
        },
        add_range_icon_click:function(sender){
          this.pageview.refs.personSelector.show(this.templateVisibleRange);
        },
        repeat_nodata_click:function() {
          this.pageview.refs.personSelector.show(this.templateVisibleRange);
        },
        at_repeat_nodata_click:function() {
            this.pageview.refs.atpersonSelector.show(this.atRange);
        },
        at_add_range_icon_click:function(sender){
            this.pageview.refs.atpersonSelector.show(this.atRange);
        },
        atpersonSelector_ok:function(sender,params){
            var selectedData = sender.selectedData;
            this.atRange = selectedData;
            this.pageview.delegate("at_tips_repeat",function(target){
                target.bindData(selectedData);
            });
            this.pageview.refs.atpersonSelector.hide();
        },
        personSelector_ok:function(sender,params){
          var selectedData = sender.selectedData;
          this.templateVisibleRange = selectedData;
          this.pageview.delegate("tips_repeat",function(target){
            target.bindData(selectedData);
          });


          this.pageview.refs.personSelector.hide();
        },

        at_tips_repeat_itemclick:function(sender,params){
            for(var i=0,j=this.atRange.length;i<j;i++){
                var item = this.atRange[i];
                if(item.dataType===1||item.dataType===3){
                    if(sender.datasource.teamId === item.teamId){
                        this.atRange.splice(i,1);
                        break;
                    }
                }else if(item.dataType===4){
                    if(sender.datasource.memberId === item.memberId){
                        this.atRange.splice(i,1);
                        break;
                    }
                }
            }
            sender.remove();
        },
        tips_repeat_itemclick:function(sender,params){
          for(var i=0,j=this.templateVisibleRange.length;i<j;i++){
            var item = this.templateVisibleRange[i];
            if(item.dataType===1||item.dataType===3){
              if(sender.datasource.teamId === item.teamId){
                this.templateVisibleRange.splice(i,1);
                break;
              }
            }else if(item.dataType===4){
              if(sender.datasource.memberId === item.memberId){
                this.templateVisibleRange.splice(i,1);
                break;
              }
            }
          }
          sender.remove();
        },
    };
    return pageLogic;
});
